import CloudIcons from '@/assets/ImageUrlConfig'
import { UpdateArticleApi, AddArticleApi, GetArticleApi } from '@/api/index'

Page({
	data: {
		ToolBarItems: [
			{ url: CloudIcons.picture, key: 'image', active: false },
			{ url: CloudIcons.header, key: 'header' },
			{ url: CloudIcons.alignLeft, key: 'align' },
			{ url: CloudIcons.fontColor, key: 'color' },
			{ url: CloudIcons.fontBold, key: 'bold' },
			{ url: CloudIcons.fontItalic, key: 'italic' },
			{ url: CloudIcons.fontUnderline, key: 'underline' },
			{ url: CloudIcons.fontStrike, key: 'strike' },
			{ url: CloudIcons.undo, url_dis: CloudIcons.undoDis, key: 'undo' },
			{ url: CloudIcons.redo, url_dis: CloudIcons.redoDis, key: 'redo' },
			{ url: CloudIcons.delete, key: 'clear' },
		],
		title: '',
		isShowToolBar: false,
		isShowHeaderPanel: false,
		isShowAlginPanel: false,
		isShowColorPanel: false,
		eidtorStatus: {},
		html: '',
		enableUndo: false,
		enableRedo: false,
		noChange: true,
		articleid: '',
	},
	onLoad({ articleid }) {
		this.setData({
			articleid,
		})
		if (articleid) {
			this.getArticle(articleid)
		}
	},
	onUnload() {
		const eventChannel = this.getOpenerEventChannel()
		eventChannel.emit('reciveArticle', {
			content: this.data.html,
			title: this.data.title,
		})
	},
	/**
	 * 获取文章
	 * @param {String} id
	 */
	getArticle(id) {
		GetArticleApi({
			id,
		})
			.then(({ content, title }) => {
				this.setData({
					html: content,
					title,
				})
				this.editorContext?.setContents({
					html: content,
				})
			})
			.catch(() => {
				wx.showToast({
					title: '连接异常',
					icon: 'error',
					duration: 1000,
				})
			})
	},
	catchtouchendVoid(e) {
		this.editorContext.format()
	},
	/**
	 * 事件分发
	 * @param {string} key
	 */
	onCatchtouchend(e) {
		const map = new Map([
			['image', this.pictureHandler],
			['header', this.headerHandler],
			['align', this.alignHandler],
			['color', this.colorHandler],
			['bold', this.boldHandler],
			['italic', this.italicHandler],
			['underline', this.underlineHandle],
			['strike', this.strikeHandler],
			['redo', this.redoHandler],
			['undo', this.undoHandler],
			['clear', this.clearHandler],
		])
		const key = e.target.dataset.key
		map.get(key)?.()
	},
	onInputTitle(e) {
		this.setData({
			noChange: false,
		})
		const title = e.detail.value
		this.setData({
			title,
		})
	},
	onInputContent(e) {
		this.setData({
			noChange: false,
		})
		const newHtml = e.detail.html
		this.setData({
			html: newHtml,
			enableUndo: true,
		})
	},
	pictureHandler() {
		this.closeAllCard()
		this.insertImageToEditor()
	},
	headerHandler() {
		this.setData({
			isShowHeaderPanel: !this.data.isShowHeaderPanel,
			isShowAlginPanel: false,
			isShowColorPanel: false,
		})
	},
	alignHandler() {
		this.setData({
			isShowAlginPanel: !this.data.isShowAlginPanel,
			isShowColorPanel: false,
			isShowHeaderPanel: false,
		})
	},
	colorHandler() {
		this.setData({
			isShowColorPanel: !this.data.isShowColorPanel,
			isShowAlginPanel: false,
			isShowHeaderPanel: false,
		})
	},
	boldHandler() {
		this.closeAllCard()
		this.formatEditor('bold')
	},
	italicHandler() {
		this.closeAllCard()
		this.formatEditor('italic')
	},
	underlineHandle() {
		this.closeAllCard()
		this.formatEditor('underline')
	},
	strikeHandler() {
		this.closeAllCard()
		this.formatEditor('strike')
	},
	undoHandler() {
		this.closeAllCard()
		const htmlBeforeChange = this.data.html
		this.editorContext.undo()
		const enableUndo = this.data.html !== htmlBeforeChange
		this.setData({
			enableRedo: true,
			enableUndo,
		})
	},
	redoHandler() {
		this.closeAllCard()
		this.editorContext.redo()
	},
	clearHandler() {
		this.closeAllCard()
		this.editorContext.clear()
		this.setData({
			title: '',
		})
	},
	onFocusEditor() {
		this.setData({
			isShowToolBar: true,
		})
	},
	onBlurEditor() {
		this.closeAllCard()
		this.setData({
			isShowToolBar: false,
		})
	},
	/**
	 * 点击设置标题
	 */
	onFocusTitle() {
		this.closeAllCard()
	},
	onBlurTitle() {},
	/**
	 * 关闭所有卡片
	 */
	closeAllCard() {
		this.setData({
			isShowColorPanel: false,
			isShowAlginPanel: false,
			isShowHeaderPanel: false,
		})
	},
	/**
	 * 初始化编辑器
	 */
	editorReady() {
		wx.createSelectorQuery()
			.select('#editor')
			.context((res) => {
				this.editorContext = res.context
				const html = this.data.html
				this.editorContext.setContents({
					html,
				})
			})
			.exec()
	},
	/**
	 * 编辑器内容发生变化
	 * @param {{
	 * 	detail: 鼠标光标位置文本的属性
	 * }} event
	 */
	onStatusChange(event) {
		this.setData({
			eidtorStatus: event.detail,
		})
	},
	/**
	 * 格式化
	 * @param {string} key
	 * @param {string} value
	 */
	formatEditor(key, value) {
		this.editorContext.format(key, value)
	},
	onBindFormat(e) {
		const { key, data } = e.detail
		this.formatEditor(key, data)
	},
	/**
	 * 插入图片
	 */
	insertImageToEditor() {
		wx.chooseMedia({
			count: 1,
			sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
			mediaType: ['image'],
			sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有，在H5浏览器端支持使用 `user` 和 `environment`分别指定为前后摄像头
			success: (res) => {
				let tmpPath = res.tempFiles[0].tempFilePath
				this.uploadImage(tmpPath).then((url) => {
					this.editorContext
						?.insertImage({
							src: url,
							extClass: 'insert-image',
						})
						.catch(() => {
							wx.showToast({
								title: '插入图片失败',
								icon: 'error',
								duration: 1000,
							})
						})
				})
			},
		})
	},
	/**
	 * 上传图片
	 * @param {String} url
	 */
	uploadImage(url) {
		return new Promise((resolve, rejects) => {
			const fileName = url.split('/').pop()
			wx.cloud
				.uploadFile({
					cloudPath: `gaga-notebook/article/${fileName}`,
					filePath: url,
				})
				.then((res) => resolve(res.fileID))
				.catch((err) => {
					rejects(err.errMsg)
					throw err
				})
		})
	},
})
